package com.webside.playbackstatistics.controller;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.LimitOperation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.group;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.match;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.project;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.sort;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.webside.Advertisingstatistics.service.AdDailyStatService;
import com.webside.Advertisingstatistics.service.AdbrowerRecordsService;
import com.webside.base.basecontroller.BaseController;
import com.webside.playbackstatistics.config.PlayStatisticsConfig;
import com.webside.playbackstatistics.model.AnaDailyStatEntity;
import com.webside.playbackstatistics.model.AnaSummaryStatEntity;
import com.webside.playbackstatistics.model.AntistopEntity;
import com.webside.playbackstatistics.model.BrowerUrlRank;
import com.webside.playbackstatistics.model.SeriesStatEntity;
import com.webside.playbackstatistics.model.SpreadBrowerRecords;
import com.webside.playbackstatistics.model.SpreadRank;
import com.webside.playbackstatistics.model.StatRankings;
import com.webside.playbackstatistics.service.AnaSummaryStatService;
import com.webside.playbackstatistics.service.DictionaryService;
import com.webside.playbackstatistics.service.PlayStatisticsService;
import com.webside.playbackstatistics.service.SeriesStatService;
import com.webside.series.model.Bdictionary;
import com.webside.util.Common;

/***
 *
 * @author Administrator lpz播放统计
 */
@Controller
@Scope("prototype")
@RequestMapping("/playstat/")
public class PlayStatisticsController extends BaseController {
	@Autowired
	private MongoTemplate mongoTemplate;
	@Autowired
	private PlayStatisticsService playStatisticsService;
	@Autowired
	private SeriesStatService seriesStatService;
	@Autowired
	DictionaryService dictionaryService;
	@Autowired
	AnaSummaryStatService anaSummaryStatService;
	@Autowired
	private AdbrowerRecordsService adbrowerRecordsService;
	@Autowired
	private AdDailyStatService adDailyStatService;
	@RequestMapping("listUI.html")
	public String selectAllPlayStat(Model model, HttpServletRequest request) {
		//添加剧集统计记录
		//anaSummaryStatService.addAnaSummaryStat();
		// playStatisticsService.selectAllPlayStat();
		// playStatisticsService.selectSumCollectStat();
		// playStatisticsService.selectSumTodayOrYesterday();
		// playStatisticsService.getAnaDailyStatList();
		// 获取平台概况信息
		List<AnaDailyStatEntity> anaDailyStatList = playStatisticsService.getAnaDailyStatList();
		for (AnaDailyStatEntity anaDailyStat : anaDailyStatList) {

			switch (anaDailyStat.getMark()) {
			// 1代表今日统计数据
			case 1:
				model.addAttribute("newDayStat", anaDailyStat);
				// 2代表昨日统计数据
			case 2:
				model.addAttribute("yesterdayStat", anaDailyStat);
				// 3代表历史每日平均值
			case 3:
				model.addAttribute("avgStat", anaDailyStat);
				// 4代表历史每日平均值
			case 4:
				model.addAttribute("maxStat", anaDailyStat);
			}

		}
		// 默认查询当天的浏览量（折线图）
		Date newDay = null;
		String seriesName = "";
		Map map = playStatisticsService.hourCount(newDay, seriesName);
		model.addAttribute("newToday", map.get("newToday")); // 当前时间的数据
		model.addAttribute("newTodayTime", map.get("newTodayTime"));// 前台显示的当前时间
		model.addAttribute("yesterday", map.get("yesterday"));// 前一天的数据
		model.addAttribute("yesterdayTime", map.get("yesterdayTime"));// 前一天的时间
		// 饼形图
		// 获取频道类型下拉框数据
		List<Bdictionary> channelList = dictionaryService.dictionaryList("channel","");
		model.addAttribute("channelList", channelList); // 频道类型
		Bdictionary bdictionary = new Bdictionary();// 初始化参数
		bdictionary.setType(PlayStatisticsConfig.channel);
		List<SeriesStatEntity> seriesStatList = seriesStatService.statPlaySum(bdictionary);
		model.addAttribute("seriesStatList", seriesStatList); // 通过频道统计的集合数据
//		Date today = new Date();
//		adbrowerRecordsService.selectSumCollectStat("",today);
		//adDailyStatService.addadDailyStat();
		adDailyStatService.avgAdDailyStatCount();
		// 剧集点播排名
		Map rankings = new HashMap();
		List<StatRankings> rankingList = new ArrayList<StatRankings>();// 获取排行信息\
		List<AnaSummaryStatEntity> risingIndexRK = new ArrayList<AnaSummaryStatEntity>();// 获取热剧预告排名
		StatRankings statRankings = new StatRankings();
		// 初始默认查询当天所有的数据排名
		statRankings.setFrame("日");
		statRankings.setChannel(PlayStatisticsConfig.channel);
		rankings = playStatisticsService.statRankings(statRankings);
		rankingList = (List)rankings.get("ranking");
		model.addAttribute("rankingList", rankingList); // 将当天所有的排名数据添加到model
		// 热剧预告根据上升指数进行排名 默认统计日上升也就是昨天和前天进行的对比数据
		// 参数默认查询日的热剧排行
		AnaSummaryStatEntity anaSummary = new AnaSummaryStatEntity();
		anaSummary.setMark("日");
		risingIndexRK = anaSummaryStatService.selectAnaRisingIndexAll(anaSummary);
		model.addAttribute("risingIndexRK", risingIndexRK); // 将昨日和前日对比得出的热据预告排行数据存入model
		// 搜索关键词统计默认统计日
		List<AntistopEntity> antistopList = new ArrayList<AntistopEntity>();
		String frame = "日";
		antistopList = playStatisticsService.antistopRanking(frame);
		model.addAttribute("antistopList", antistopList); // 将关键词统计数据插入model
		return Common.BACKGROUND_PATH + "/playstatistisc/list";

	}

	@RequestMapping("fromSpreadCount.html")
	@ResponseBody
	public Object fromSpreadCount(Model model, HttpServletRequest request) {
		Query query=new Query();
		Long count=mongoTemplate.count(query, "spread_brower_records");
		LimitOperation limitOperation=new LimitOperation(10);
		Aggregation aggregation=newAggregation(
				group("spreadSupportCode").count().as("total"),
				project("total").and("spreadSupportCode").previousOperation(),
				sort(Sort.Direction.DESC, "total"),limitOperation
				);
		AggregationResults<SpreadRank> groupResults = mongoTemplate.aggregate(aggregation, "spread_brower_records", SpreadRank.class);
		List<SpreadRank> list=groupResults.getMappedResults();
		System.out.println(list.size()+"=================");
		
		for (SpreadRank spreadRank : list) {
			/*spreadRank.setPercent();*/
			DecimalFormat decimalFormat=new DecimalFormat(".0");
			spreadRank.setPercent(decimalFormat.format(Math.ceil((spreadRank.getTotal()/(float)count)*1000)/10)+"%");
		}
		return list;
	}
	@RequestMapping("fromUrlCount.html")
	@ResponseBody
	public Object fromUrlCount(Model model, HttpServletRequest request) {
		Query query=new Query();
		Long count=mongoTemplate.count(query, "spread_brower_records");
		LimitOperation limitOperation=new LimitOperation(10);
		Aggregation aggregation=newAggregation(
				group("browerUrl").count().as("total"),
				project("total").and("browerUrl").previousOperation(),
				sort(Sort.Direction.DESC, "total"),limitOperation
				);
		AggregationResults<BrowerUrlRank> groupResults = mongoTemplate.aggregate(aggregation, "spread_brower_records", BrowerUrlRank.class);
		List<BrowerUrlRank> list=groupResults.getMappedResults();
		System.out.println(list.size()+"=================");
		
		for (BrowerUrlRank spreadRank : list) {
			/*spreadRank.setPercent();*/
			DecimalFormat decimalFormat=new DecimalFormat(".0");
			spreadRank.setPercent(decimalFormat.format(Math.ceil((spreadRank.getTotal()/(float)count)*1000)/10)+"%");
		}
		return list;
	}
	@RequestMapping("NamelistUI.html")
	@ResponseBody
	public Object selectAllPlayStatName(Model model, HttpServletRequest request, String name) {
		// 获取平台概况信息
		List<AnaDailyStatEntity> anaDailyStatList = null;
		if (null != name && !name.equals("")) {

			anaDailyStatList = playStatisticsService.getAnaDailyStatNameList(name);
		} else {

			anaDailyStatList = playStatisticsService.getAnaDailyStatList();
		}

		Map map = new HashMap();

		// 将插寻到的数据存入map中 供回调
		for (AnaDailyStatEntity anaDailyStat : anaDailyStatList) {

			switch (anaDailyStat.getMark()) {
			// 1代表今日统计数据
			case 1:
				map.put("newDayStat", anaDailyStat);
				// 2代表昨日统计数据
			case 2:
				map.put("yesterdayStat", anaDailyStat);
				// 3代表历史每日平均值
			case 3:
				map.put("avgStat", anaDailyStat);
				// 4代表历史每日平均值
			case 4:
				map.put("maxStat", anaDailyStat);
			}

		}

		return map;

	}
	
	// 根据日期查询当天浏览量折线图
	@RequestMapping("zheXianlistUI.html")
	@ResponseBody
	public Object selectAllPlayStatZhe(Model model, HttpServletRequest request, String name, String time) {
		// 设置时间格式
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date newDay = null;
		String seriesName = "";

		if (null != time && !time.equals("")) {

			try {
				newDay = df.parse(time);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		if (null != name && !name.equals("")) {

			seriesName = name;
		}

		Map map = playStatisticsService.hourCount(newDay, seriesName);

		return map;

	}

	// 根据类型查询饼形图数据
	@RequestMapping("binTulistUI.html")
	@ResponseBody
	public Object statPlaySumBinTu(Model model, HttpServletRequest request, String channel, String kindType) {
		JSONArray gResTable = new JSONArray();
		if (null != channel && !channel.equals("")) {
			// 声明json对象数组
			if (channel.equals("全频道")) {
				channel = PlayStatisticsConfig.channel;
				kindType = "";
			} else if (channel.equals("电影")) {
				switch (kindType) {

				case "剧集分类":
					channel = PlayStatisticsConfig.kind;
					kindType = PlayStatisticsConfig.movie;
					break;
				case "剧情分类":
					channel = PlayStatisticsConfig.type;
					kindType = PlayStatisticsConfig.movie;
					break;

				}

			} else if (channel.equals("电视剧")) {
				switch (kindType) {

				case "剧集分类":
					channel = PlayStatisticsConfig.kind;
					kindType = PlayStatisticsConfig.tvplay;
					break;
				case "剧情分类":
					channel = PlayStatisticsConfig.type;
					kindType = PlayStatisticsConfig.tvplay;
					break;

				}
			} else if (channel.equals("动漫")) {
				switch (kindType) {

				case "剧集分类":
					channel = PlayStatisticsConfig.kind;
					kindType = PlayStatisticsConfig.cartoon;
					break;
				case "剧情分类":
					channel = PlayStatisticsConfig.type;
					kindType = PlayStatisticsConfig.cartoon;
					break;

				}

			}
			List<SeriesStatEntity> seriesStatList = new ArrayList();
			Bdictionary bdictionary = new Bdictionary();

			bdictionary.setType(channel);
			bdictionary.setCode(kindType);

			if (channel.equals(PlayStatisticsConfig.channel)) {
				seriesStatList = seriesStatService.statPlaySum(bdictionary);
				if (null != seriesStatList) {
					for (SeriesStatEntity series : seriesStatList) {
						JSONObject node = new JSONObject();
						node.put("name", series.getChannel());
						node.put("value", series.getPlayCount());
						gResTable.add(node);
					}

				}
			} else if (channel.equals(PlayStatisticsConfig.kind)) {
				seriesStatList = seriesStatService.statPlaySum(bdictionary);
				if (null != seriesStatList) {
					for (SeriesStatEntity series : seriesStatList) {
						JSONObject node = new JSONObject();

						node.put("name", series.getKindName());
						node.put("value", series.getPlayCount());
						gResTable.add(node);
					}

				}

			} else if (channel.equals(PlayStatisticsConfig.type)) {

				seriesStatList = seriesStatService.statPlaySum(bdictionary);
				if (null != seriesStatList) {
					for (SeriesStatEntity series : seriesStatList) {
						JSONObject node = new JSONObject();

						node.put("name", series.getTypeName());
						node.put("value", series.getPlayCount());
						gResTable.add(node);
					}

				}

			}

		}
		return gResTable;

	}

	// 剧集播放排行
	@RequestMapping("rankingslistUI.html")
	@ResponseBody
	public Object statPlaySumRankings(Model model, HttpServletRequest request, String channel, String kind, String type,
			String frame) {
		Map rankings = new HashMap();
		// 创建参数列表
		StatRankings statRankings = new StatRankings();
		switch (channel) {
		case "全频道":
			statRankings.setChannel(PlayStatisticsConfig.channel);
			break;
		case "电影":
			statRankings.setChannel(PlayStatisticsConfig.movie);
			break;
		case "电视剧":
			statRankings.setChannel(PlayStatisticsConfig.tvplay);
			break;
		case "动漫":
			statRankings.setChannel(PlayStatisticsConfig.cartoon);
			break;
		}
		statRankings.setKind(kind);
		statRankings.setType(type);
		statRankings.setFrame(frame);
		rankings = playStatisticsService.statRankings(statRankings);
		//System.out.println(rankings.size());
		return rankings;

	}

	// 热剧预告排行
	@RequestMapping("hotshowlistUI.html")
	@ResponseBody
	public Object statPlaySumHotShow(Model model, HttpServletRequest request, String frame) {
		Map hotShow = new HashMap();
		List<AnaSummaryStatEntity> anaSummaryList = new ArrayList<AnaSummaryStatEntity>();
		// 创建参数
		AnaSummaryStatEntity anaSummary = new AnaSummaryStatEntity();
		anaSummary.setMark(frame.trim());
		anaSummaryList = anaSummaryStatService.selectAnaRisingIndexAll(anaSummary);
		hotShow.put("hotShowList", anaSummaryList);
		return hotShow;

	}

	// 搜索关键词排行
	@RequestMapping("antistoplistUI.html")
	@ResponseBody
	public Object statPlaySumAntistop(Model model, HttpServletRequest request, String frame) {
		Map antistop = new HashMap();
		List<AntistopEntity> antistopList = new ArrayList<AntistopEntity>();
		// 创建参数
		antistopList = playStatisticsService.antistopRanking(frame);
		antistop.put("antistopList", antistopList);
		return antistop;

	}

}
